﻿using Microsoft.Web.WebView2.Core;
using System.Diagnostics;
using System;
using System.Windows.Controls;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Newtonsoft.Json;
using WPFNote.Utilities.Common;
using WPFNote.ViewModels;

namespace WPFNote.Views
{
    public partial class NoteEdit : UserControl
    {
        private bool _isInit = false;

        public NoteEdit()
        {
            InitializeComponent();
            Init();
        }

        private void NoteEdit_OnLoaded(object sender, RoutedEventArgs e)
        {
            Task.Run(SetValue);
        }

        private void NoteEdit_OnSizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (!_isInit)
            {
                return;
            }
            SetWebViewHeight();
        }

        private async void Init()
        {
            WebBrowser.Source = new Uri("file:///" +
                                        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Html", "editor.html")
                                            .Replace("\\", "/"));
            await WebBrowser.EnsureCoreWebView2Async(null);
            WebBrowser.CoreWebView2.WebMessageReceived -= Wv2_WebMessageReceived;
            WebBrowser.CoreWebView2.WebMessageReceived += Wv2_WebMessageReceived;
            _isInit = true;
        }

        private async void SetValue()
        {
            var isFirst = false;
            while (!_isInit)
            {
                isFirst = true;
                Thread.Sleep(100);
            }

            await Application.Current.Dispatcher.Invoke(async () =>
            {
                if (DataContext is NoteEditViewModel data)
                {
                    await SetWebViewContent(data);
                    // 如果首次加载，则设置两次数据
                    if (isFirst)
                    {
                        await SetWebViewContent(data);
                    }
                }
            });
        }

        private async Task SetWebViewContent(NoteEditViewModel data)
        {
            Thread.Sleep(100);
            SetWebViewHeight();
            var base64String = EncryptionHelper.EncodeBase64(data.Content);
            await WebBrowser.CoreWebView2.ExecuteScriptAsync($"setMarkdown('{base64String}');");
        }

        private void Wv2_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
        {
            //接收到的字符串
            var msg = e.TryGetWebMessageAsString();
            if (DataContext is NoteEditViewModel data)
            {
                data.Content = msg;
            }
        }

        private async void SetWebViewHeight()
        {
            var height = this.ActualHeight - 80;
            await WebBrowser.CoreWebView2.ExecuteScriptAsync($"setHeight('{height}px');");
        }
    }
}